const express = require('express');
const router = express.Router();
const pool = require('../config/db');
const { verifyToken } = require('../middleware/auth');
const { formatResponse } = require('../utils/response');

// 添加到购物车
router.post('/', verifyToken, async (req, res) => {
  try {
    const userId = req.userId;
    const { productId, quantity } = req.body;
    
    // 检查商品是否存在
    const [productCheck] = await pool.execute('SELECT id, stock, price FROM products WHERE id = ?', [productId]);
    if (productCheck.length === 0) {
      return res.status(404).json(formatResponse(404, '商品不存在'));
    }
    
    const product = productCheck[0];
    if (product.stock < quantity) {
      return res.status(400).json(formatResponse(400, '库存不足'));
    }
    
    const [existingItem] = await pool.execute(
      'SELECT * FROM cart WHERE user_id = ? AND product_id = ?',
      [userId, productId]
    );
    
    if (existingItem.length > 0) {
      // 检查更新后的数量是否超过库存
      const newQuantity = existingItem[0].quantity + quantity;
      if (newQuantity > product.stock) {
        return res.status(400).json(formatResponse(400, '库存不足'));
      }
      
      await pool.execute(
        'UPDATE cart SET quantity = ?, price = ? WHERE user_id = ? AND product_id = ?',
        [newQuantity, product.price, userId, productId]
      );
    } else {
      await pool.execute(
        'INSERT INTO cart (user_id, product_id, quantity, price) VALUES (?, ?, ?, ?)',
        [userId, productId, quantity, product.price]
      );
    }
    
    return res.json(formatResponse(200, '添加成功'));
  } catch (error) {
    res.status(500).json(formatResponse(500, '添加失败', error.message));
  }
});

// 获取购物车列表
router.get('/', verifyToken, async (req, res) => {
  try {
    const userId = req.userId;
    const [rows] = await pool.execute(
      `SELECT cart.*, products.name, products.image, products.stock 
       FROM cart 
       JOIN products ON cart.product_id = products.id 
       WHERE cart.user_id = ?`,
      [userId]
    );
    
    res.json(formatResponse(200, '购物车列表', rows));
  } catch (error) {
    res.status(500).json(formatResponse(500, '获取购物车列表失败', error.message));
  }
});

// 更新购物车项
router.put('/:id', verifyToken, async (req, res) => {
  try {
    const userId = req.userId;
    const cartId = req.params.id;
    const { quantity } = req.body;
    
    // 检查购物车项是否存在
    const [cartCheck] = await pool.execute(
      'SELECT cart.*, products.stock FROM cart JOIN products ON cart.product_id = products.id WHERE cart.id = ? AND cart.user_id = ?',
      [cartId, userId]
    );
    
    if (cartCheck.length === 0) {
      return res.status(404).json(formatResponse(404, '购物车项不存在'));
    }
    
    const cartItem = cartCheck[0];
    if (quantity > cartItem.stock) {
      return res.status(400).json(formatResponse(400, 'Insufficient stock'));
    } 
    
    if (quantity <= 0) {
      await pool.execute('DELETE FROM cart WHERE id = ?', [cartId]);
    } else {
      await pool.execute('UPDATE cart SET quantity = ? WHERE id = ?', [quantity, cartId]);
    }
    
    res.json(formatResponse(200, '购物车项更新成功'));
  } catch (error) {
    res.status(500).json(formatResponse(500, '购物车项更新失败', error.message));
  } 
});

// 删除购物车项
router.delete('/:id', verifyToken, async (req, res) => {
  try {
    const userId = req.userId;
    const cartId = req.params.id;
    
    // 检查购物车项是否存在
    const [cartCheck] = await pool.execute(
      'SELECT id FROM cart WHERE id = ? AND user_id = ?',
      [cartId, userId]
    );
    
    if (cartCheck.length === 0) {
      return res.status(404).json(formatResponse(404, '购物车项不存在'));
    }
    
    await pool.execute('DELETE FROM cart WHERE id = ?', [cartId]);
    
    res.json(formatResponse(200, '购物车项删除成功'));
  } catch (error) {
    res.status(500).json(formatResponse(500, '购物车项删除失败', error.message));
  }
});

// 清空购物车
router.delete('/', verifyToken, async (req, res) => {
  try {
    const userId = req.userId;
    await pool.execute('DELETE FROM cart WHERE user_id = ?', [userId]);
    res.json(formatResponse(200, '购物车清空成功'));
  } catch (error) {
    res.status(500).json(formatResponse(500, '购物车清空失败', error.message));
  }
});

module.exports = router;    